﻿@model JewererBasic.COMPONENT_ORDER
@using (Html.BeginForm("Index", "ComponentOrder", FormMethod.Post, new { id = "formBagControl" }))
{    
    <h2>Order Components</h2>
    @Html.HiddenFor(m => m.Id, new { id = "Component_Order_Id" })

    <fieldset>
        <legend>Add More Component</legend>
        <div id="component">
        </div>
        <p>
            <input type="button" value="Add" id="btnAdd" />
            <input type="submit" value="Finish" style="display: none" id="btnFinish" />
        </p>        
    </fieldset>
    
    <fieldset>
        <legend>Order Tree Information</legend>
        <table>
            <tr>
                <td>
                    <table class="table head">
                        <tr>
                            <th style="width: 200px;">Order Component Id</th>
                            <th style="width: 200px;">Date</th>
                            <th style="width: 200px;">MC</th>
                        </tr>
                        <tr>
                            <td style="width: 200px; text-align: center">@Html.DisplayFor(m => m.Id)</td>
                            <td style="width: 200px; text-align: center">@Html.DisplayFor(m => m.DateMake)</td>
                            <td style="width: 200px; text-align: center">@Html.DisplayFor(m => m.MC)</td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
        <!--Show current list-->
        <p></p>
        <p></p>
        <p></p>
        @if (Model.COMPONENT_ORDER_DETAIL.Count > 0)
        {
            <table class="table head tableContent">
                <tr>
                    <th style="width: 100px;">Bag Id
                    </th>
                    <th style="width: 200px;">Component Id
                    </th>
                    <th style="width: 200px;">Worker Id
                    </th>
                    <th style="width: 250px;">Time make
                    </th>
                    <th style="width: 200px;">Status
                    </th>
                    <th style="width: 200px;">Return Weight
                    </th>
                    <th style="width: 200px;">Dust Weight
                    </th>
                    <th style="width: 200px;">Actions
                    </th>
                </tr>

                @foreach (var item in Model.COMPONENT_ORDER_DETAIL)
                {
                    <tr>
                        <td style="text-align: center;">
                            @Html.DisplayFor(modelItem => item.Id)
                        </td>
                        <td style="text-align: center">
                            @Html.DisplayFor(modelItem => item.Component_Id)
                        </td>
                        <td style="text-align: center">
                            @Html.DisplayFor(modelItem => item.EMPLOYEE.Staff_Id)
                        </td>
                        <td style="text-align: center">
                            @Html.DisplayFor(m => m.DateMake)
                        </td>
                        @if (item.Finish == -1)
                        {
                            <td style="text-align: center">Not Started
                            </td>
                        }
                        else if (item.Finish == 0)
                        {
                            <td style="text-align: center">Started
                            </td>   
                        }
                        else if (item.Finish == 1)
                        {
                            <td style="text-align: center">Finish
                            </td>                       
                        }
                        <td style="text-align: center">
                            @Html.DisplayFor(modelItem => item.Return_Weight)
                        </td>
                        <td style="text-align: center">
                            @Html.DisplayFor(modelItem => item.Dust)
                        </td>
                        @if (item.Finish == -1)
                        {
                            <td style="text-align: center">
                                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                        @Html.ActionLink("Delete", "Delete", new { id = item.Id })
                            </td>
                        }
                        else
                        {
                            <td style="text-align: center">
                                @Html.ActionLink("Details", "Details", new { id = item.Id })
                            </td>
                        }
                    </tr>
                }
            </table>
        }
    </fieldset>
}
@section Scripts{
    <script src="~/Scripts/jQuery.FileUpload/jquery.fileupload.js"></script>
    <script src="~/Scripts/jQuery.FileUpload/jquery.fileupload-ui.js"></script>
    <script src="~/Scripts/jQuery.FileUpload/jquery.iframe-transport.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="@Url.Content("~/Scripts/json2.min.js")" type="text/javascript"></script>

    <script type="text/javascript">
        var index = 1;
        var indexChild = 1;
        // add new component
        $('#btnAdd').click(function () {
            //$(this).hide();
            $("#btnFinish").show();
            addComponent(index, "", "", "", "");
            index = index + 1;
        });

        // submit
        $(document).ready(function () {
            $("form").submit(function (evt) {
                // collect all information
                var flag = false;
                var data = new Array();
                $('.pTag').each(function () {
                    if (!flag) {
                        var ComponentId = $(this).children('.txtComId').val();
                        var WorkerId = $(this).children('.txtComWorker').val();
                        if (!ComponentId || !WorkerId) {
                            alert("Missing information");
                            flag = true;
                        } else {
                            var model = new COMPONENT_ORDER_DETAIL(ComponentId, WorkerId);

                            // add molecule to model
                            var ind = $(this).children('.txtHidden').val();
                            $("#divMolecule" + ind).children('.pMolecule').each(function () {
                                var Com_Slaver_Id = $(this).children('.moleculeId').val();
                                var Export_Weight = $(this).children('.moleculeWeight').val();
                                var Percentage = $(this).children('.percentage').val();
                                if (!Com_Slaver_Id && !Export_Weight) {
                                    alert("Missing information");
                                    flag = true;
                                } else {
                                    var child = new COMPONENT_ORDER_COM_MOLECULE_EXPORT(Com_Slaver_Id, Export_Weight, Percentage);
                                    model.COMPONENT_ORDER_COM_MOLECULE_EXPORT.push(child);
                                }
                            });
                            data.push(model);
                        }
                    }
                });

                // post 
                var id = $('#Component_Order_Id').val();
                if (!flag) {
                    postData = { models: data, id: id };
                    $.ajax({
                        url: '/ComponentOrder/IndexSubmit',
                        type: 'POST',
                        dataType: 'json',
                        data: JSON.stringify(postData),
                        contentType: 'application/json; charset=utf-8',
                        async: false,
                        success: function (data) {
                            if (!data.success) {
                                alert("Error in component order controller");
                                evt.preventDefault();
                            }
                        },
                        error: function (xhr, ajaxOptions, thrownError) {
                            alert("Error in Component Order View");
                            evt.preventDefault();
                        }
                    });
                }
                else {
                    evt.preventDefault();
                }
            });
        });

        // component_order_detail view
        function COMPONENT_ORDER_DETAIL(Component_Id, Worker_Id) {
            var self = this;
            self.Component_Id = Component_Id;
            self.Worker_Id = Worker_Id;
            self.COMPONENT_ORDER_COM_MOLECULE_EXPORT = new Array();
        }

        // component_order_detail_export view
        function COMPONENT_ORDER_COM_MOLECULE_EXPORT(Com_Slaver_Id, Export_Weight, Percentage) {
            var self = this;
            self.Export_Weight = Export_Weight;
            self.Com_Slaver_Id = Com_Slaver_Id;
            self.Percentage = Percentage;
        }

        // add component_order_detail function
        function addComponent(index, Item, Qty, Unit, Type) {

            // using for dropdownlist of workers
            var values;
            var texts;

            $.ajax({
                url: '/ComponentOrder/GetWorkerId',
                type: 'GET',
                contentType: 'application/json; charset=utf-8',
                async: false,
                success: function (data) {
                    var tmpStr = "";
                    tmpStr = data.values;
                    values = tmpStr.split(";");
                    tmpStr = data.texts;
                    texts = tmpStr.split(";");
                },
                error: function (xhr, ajaxOptions, thrownError) {
                }
            });

            var dropdownlist = '<select id="ddlWorkerId" class="txtComWorker" required>';
            for (var i = 0; i < values.length - 1; i++) {
                dropdownlist += '<option value="' + values[i] + '">' + texts[i] + '</option>';
            }
            dropdownlist += '</select>';

            $('#component').append('<div class="pTag">'+
                                      '<strong class="myStrong">Component Id</strong>'+
                                      '<input type="text" class="txtComId" id="txtComponentId' + index + '"  style = "width:150px;" placeholder="Component Id" required>' +
                                      '<strong class="myStrong">Worker Id</strong>' +
                                      dropdownlist +
                                      '<strong class="myStrong">Add Component</strong>' +
                                      '<input type="button" class="btnCheckClass" id="btnCheck' + index + '" value="Add Component"/>' +
                                      '<a href="#" id="remove" class="myA">Remove </a>' +
                                      '<input type="hidden" class="txtHidden" value = "' + index + '" />' +
                                      '<p/>'+
                                      '<div class="divm" id="divMolecule' + index + '"  style="padding-left: 40px; border:1px solid #000000;"/>' +
                                      '</div><p/><p/><p/><p/>');
            var componentTB = $("#txtComponentId" + index);
            $(componentTB).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/ComponentOrder/ComponentAutoComplete',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                select: function (event, ui) {
                    $(componentTB).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });

            // remove additional elements
            $(document).on("click", "#remove ", function () {
                $(this).parents('.pTag').remove();
                //$("#btnAdd").show();
                //$("#btnFinish").hide();
                var length = $("#component").children().length;
                if (length == 0) {
                    $("#btnFinish").hide();
                }
                return false;
            });
        }

        // Add component button
        $(document).on("click", ".btnCheckClass ", function () {

            // check conditions before add molecules
            var comId = $(this).parents('div').children('.txtComId').val();
            var workerId = $(this).parents('div').children('.txtComWorker').val();
            if (!comId || !workerId) {
                alert("Please fill ComponentId and WorkerId");
                return false;
            }            
            // send componentId
            $.ajax({
                url: '/ComponentOrder/GetComponentId',
                type: 'POST',
                dataType: 'json',
                data: { query: comId },
                async: false,
                success: function (data) {
                    if (!data.Success) {
                        alert("Error when transmit ComponentId");
                    }
                }
            });
                           
            // Add molecule
            var ind = $(this).parents('div').children('.txtHidden').val();
            $("#divMolecule" + ind).append('<p class="pMolecule">' +
                            '<strong class="myStrong">Component Id</strong>' +
                            '<input type="text" class="moleculeId" required id="txtMoleculeId' + indexChild + '"/>' +
                            '<strong class="myStrong">Percentage</strong>' +
                            '<input type="text" class="percentage"  required/>' +
                            '<strong class="myStrong">Weight</strong>' +
                            '<input type="text" class="moleculeWeight" style = "width:150px;" required>' +
                            '<a href="#" id="removeChild" class="myA">Remove </a>' +
                            '</p>');

            // remove additional elements
            $(document).on("click", "#removeChild", function () {
                $(this).parents('.pMolecule').remove();                
                return false;
            });
            var txt=$("#txtMoleculeId"+indexChild);
            $(txt).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: '/ComponentOrder/ComponentAutoComplete',
                        data: { query: request.term },
                        dataType: 'json',
                        type: 'GET',
                        success: function (data) {
                            response($.map(data, function (item) {
                                return {
                                    label: item,
                                    value: item
                                }
                            }));
                        },
                    })
                },
                select: function (event, ui) {
                    $(txt).val(ui.item.label);
                    return false;
                },
                minLength: 1
            });
            indexChild+=1;
        });       
    </script>
}
